package org.xenon.vote.dao.imp;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.xenon.vote.dao.IntDao;
import org.xenon.vote.model.pojo.po.Turn;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class TurnDao implements IntDao<Turn> {

    private final JdbcTemplate jdbcTemplate;

    public TurnDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    @Override
    public void add(Turn turn) {
        String sql = "insert into `vote`.`turn` (`order`, `ballot`, `limit`, `option`) values (?, ?, ?, ?)";
        jdbcTemplate.update(sql, turn.getOrder(), turn.getBallot(), turn.getLimit(), turn.getOption());
    }

    @Override
    public void edit(Turn turn) {
        String sql = "update `vote`.`turn` set `order` = ? , `ballot` = ? , `limit` = ?, `option` = ? where `id` = ?";
        jdbcTemplate.update(sql, turn.getOrder(), turn.getBallot(), turn.getLimit(), turn.getOption(), turn.getId());
    }

    @Override
    public Turn get(int id) {
        String sql = "select * from `vote`.`turn` where `id` = ?";
        List<Turn> list = jdbcTemplate.query(sql, new Object[]{id}, TurnRowMapper.getInstance());
        if (list.size() == 0) return null;
        return list.get(0);
    }

    @Override
    public List<Turn> getAll(int ballot) {
        String sql = "select * from `vote`.`turn` where `ballot` = ? order by id desc ";
        return jdbcTemplate.query(sql, new Object[]{ballot}, TurnRowMapper.getInstance());
    }

    @Override
    public void del(Turn turn) {
        String sql = "delete FROM `vote`.`turn` WHERE `id` = ?";
        jdbcTemplate.update(sql,turn.getId());
    }

    @Override
    public void del(int id) {
        String sql = "delete FROM `vote`.`turn` WHERE `id` = ?";
        jdbcTemplate.update(sql,id);
    }

    /**
     * 自动以RowMapper
     * 提高性能, 使用单例模式
     */
    private static class TurnRowMapper implements RowMapper<Turn> {

        private static TurnRowMapper turnRowMapper;
        @Override
        public Turn mapRow(ResultSet rs, int i) throws SQLException {
            return new Turn(rs.getInt("id"),
                    rs.getInt("order"),
                    rs.getInt("ballot"),
                    rs.getInt("limit"),
                    rs.getInt("option"));
        }

        static TurnRowMapper getInstance(){
            if (turnRowMapper == null){
                synchronized (TurnRowMapper.class){
                    if(turnRowMapper==null){
                        turnRowMapper = new TurnRowMapper();
                    }
                }
            }
            return turnRowMapper;
        }
    }
}
